/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkInvokeStmt, ArkMethod, DEFAULT_ARK_CLASS_NAME, Stmt } from 'arkanalyzer/lib';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import { ArkClass } from 'arkanalyzer/lib/core/model/ArkClass';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { Rule, Defects, ClassMatcher, MatcherTypes, MatcherCallback, CheckerUtils } from '../../Index';
import { IssueReport } from '../../model/Defects';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ReasonableGpsUseCheck');
const gMetaData: BaseMetaData = {
    severity: 3,
    ruleDocPath: 'docs/reasonable-gps-use-check.md',
    description: 'Apps that do not have a long task are pushed back to the background and are prohibited from using location services.'
};

const onSignature = `@ohosSdk/api/@ohos.geoLocationManager.d.ts: geoLocationManager.${DEFAULT_ARK_CLASS_NAME}.on('locationChange', @ohosSdk/api/@ohos.geoLocationManager.d.ts: geoLocationManager.LocationRequest|@ohosSdk/api/@ohos.geoLocationManager.d.ts: geoLocationManager.ContinuousLocationRequest, @ohosSdk/api/@ohos.base.d.ts: Callback<@ohosSdk/api/@ohos.geoLocationManager.d.ts: geoLocationManager.Location>)`;
const offSignature = `@ohosSdk/api/@ohos.geoLocationManager.d.ts: geoLocationManager.${DEFAULT_ARK_CLASS_NAME}.off('locationChange', @ohosSdk/api/@ohos.base.d.ts: Callback<@ohosSdk/api/@ohos.geoLocationManager.d.ts: geoLocationManager.Location>)`;
const backgroundSignature: string[] = [
    `@ohosSdk/api/@ohos.resourceschedule.backgroundTaskManager.d.ts: backgroundTaskManager.${DEFAULT_ARK_CLASS_NAME}.startBackgroundRunning(@ohosSdk/api/application/BaseContext.d.ts: BaseContext, @ohosSdk/api/@ohos.resourceschedule.backgroundTaskManager.d.ts: backgroundTaskManager.BackgroundMode, @ohosSdk/api/@ohos.wantAgent.d.ts: ${DEFAULT_ARK_CLASS_NAME}.[static]${DEFAULT_ARK_CLASS_NAME}()#WantAgent, @ohosSdk/api/@ohos.base.d.ts: AsyncCallback<void,void>)`,
    `@ohosSdk/api/@ohos.resourceschedule.backgroundTaskManager.d.ts: backgroundTaskManager.${DEFAULT_ARK_CLASS_NAME}.startBackgroundRunning(@ohosSdk/api/application/BaseContext.d.ts: BaseContext, @ohosSdk/api/@ohos.resourceschedule.backgroundTaskManager.d.ts: backgroundTaskManager.BackgroundMode, @ohosSdk/api/@ohos.wantAgent.d.ts: ${DEFAULT_ARK_CLASS_NAME}.[static]${DEFAULT_ARK_CLASS_NAME}()#WantAgent)`,
    `@ohosSdk/api/@ohos.resourceschedule.backgroundTaskManager.d.ts: backgroundTaskManager.${DEFAULT_ARK_CLASS_NAME}.startBackgroundRunning(@ohosSdk/api/application/BaseContext.d.ts: BaseContext, string[], @ohosSdk/api/@ohos.wantAgent.d.ts: ${DEFAULT_ARK_CLASS_NAME}.[static]${DEFAULT_ARK_CLASS_NAME}()#WantAgent)`
];

export class ReasonableGpsUseCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private clsMatcher: ClassMatcher = {
        matcherType: MatcherTypes.CLASS
    };

    public registerMatchers(): MatcherCallback[] {
        const matchClassCb: MatcherCallback = {
            matcher: this.clsMatcher,
            callback: this.check
        };
        return [matchClassCb];
    }

    public check = (targetCla: ArkClass): void => {
        for (let method of targetCla.getMethods()) {
            if (this.hasBackgroundMethodCall(method)) {
                return;
            }
        }
        let foregroundMethod = targetCla.getMethodWithName('onForeground');
        let backgroundMethod = targetCla.getMethodWithName('onBackground');
        if (!foregroundMethod) {
            return;
        }
        let foregroundStmt = this.hasMethodSignatureInStatements(foregroundMethod, onSignature);
        if (foregroundStmt) {
            if (!backgroundMethod || !this.hasMethodSignatureInStatements(backgroundMethod, offSignature)) {
                this.reportIssue(foregroundStmt, 'on');
            }
        }
    };

    private hasBackgroundMethodCall(method: ArkMethod, checkedMethods = new Set<string>()): boolean {
        let stmts = method.getBody()?.getCfg().getStmts();
        if (!stmts) {
            return false;
        }
        for (let stmt of stmts) {
            if (!(stmt instanceof ArkInvokeStmt)) {
                continue;
            }
            let invoker = stmt.getInvokeExpr();
            let signature = invoker.getMethodSignature().toString();
            if (backgroundSignature.includes(signature)) {
                return true;
            }
            if (!checkedMethods.has(signature)) {
                checkedMethods.add(signature);
                let invokedMethod = method.getDeclaringArkFile().getScene().getMethod(invoker.getMethodSignature());
                if (invokedMethod && this.hasBackgroundMethodCall(invokedMethod, checkedMethods)) {
                    return true;
                }
            }
        }
        return false;
    }

    public hasMethodSignatureInStatements(method: ArkMethod, signature: string): Stmt | null {
        const stmts = method.getBody()?.getCfg().getStmts();
        if (!stmts) {
            return null;
        }
        const stack = [{ method, stmts: stmts }];
        while (stack.length > 0) {
            const { method, stmts } = stack.pop()!;
            for (const stmt of stmts) {
                const invoker = CheckerUtils.getInvokeExprFromStmt(stmt);
                if (!invoker) {
                    continue;
                }
                if (invoker.getMethodSignature().toString() === signature) {
                    return stmt;
                }
                const invMethod = method.getDeclaringArkFile().getScene().getMethod(invoker.getMethodSignature());
                if (invMethod) {
                    stack.push({ method: invMethod, stmts: invMethod.getBody()?.getCfg().getStmts() || [] });
                }
            }
        }
        return null;
    }

    private reportIssue(stmt: Stmt, methodName: string): void {
        const severity = this.rule.alert ?? this.metaData.severity;
        const filePath = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile().getFilePath();
        const originPositionInfo = stmt.getOriginPositionInfo();
        const lineNum = originPositionInfo.getLineNo();
        const text = stmt.getOriginalText();
        if (!text || text.length === 0) {
            return;
        }
        const startColumn = originPositionInfo.getColNo() + text.indexOf(methodName);
        const endColunm = startColumn + methodName.length - 1;
        let defects = new Defects(lineNum, startColumn, endColunm, this.metaData.description, severity, this.rule.ruleId,
            filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defects, undefined));
    }
}